﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace He.Common
{
    /// <summary>
    /// 字符串操作辅助类
    /// </summary>
    public class StringHelper
    {

        #region 移位操作

        /// <summary>
        /// 将字符串循环左移
        /// </summary>
        /// <param name="old">旧的字符串</param>
        /// <param name="num">移动几位</param>
        /// <returns>循环左移后的字符串</returns>
        public static string RingShiftLeft(string old, int num)
        {
            if (string.IsNullOrEmpty(old))
                return string.Empty;

            int n = num % old.Length;
            return old.Substring(n) + old.Substring(0, n);
        }

        /// <summary>
        /// 将字符串循环右移
        /// </summary>
        /// <param name="old">旧的字符串</param>
        /// <param name="num">移动几位</param>
        /// <returns>循环右移后的字符串</returns>
        public static string RingShiftRight(string old, int num)
        {
            if (string.IsNullOrEmpty(old))
                return string.Empty;

            int n = num % old.Length;
            return old.Substring(old.Length - n, n) + old.Substring(0, old.Length - n);
        }

        #endregion

        #region html字符串处理
        //public string readonly DefaultAllowTags;

        /// <summary>
        /// 剥去白名单以外的HTML标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="allowTags"></param>
        /// <returns>相对安全的HTML字符串</returns>
        ///
        /// PHP原型：strip_tags(string,allow)
        ///
        public static string StripTags(string html, string[] allowTags)
        {
            html = HttpUtility.HtmlEncode(html);

            //TODO:解开白名单标签

            return html;
        }

        /// <summary>
        /// 将文本中出现的html标签剥去
        /// </summary>
        /// <param name="htmlString"></param>
        /// <returns></returns>
        public static string StripTags(string htmlString)
        {
            //删除脚本  
            htmlString = Regex.Replace(htmlString, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML  
            htmlString = Regex.Replace(htmlString, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"-->", "", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"<!--.*", "", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlString = Regex.Replace(htmlString, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            htmlString.Replace("<", "");
            htmlString.Replace(">", "");
            htmlString = HttpUtility.HtmlEncode(htmlString).Trim();
            return htmlString;
        }

        /// <summary>
        /// 将文本中出现的html标签剥去
        /// </summary>
        /// <param name="html">html文本</param>
        /// <returns>返回不带html标签的字符串</returns>
        public static string ClearHtmlTags(string html)
        {
            return StripTags(html);
        }

        /// <summary>
        /// 将文本中出现的html标签剥去,并截取指定长度
        /// </summary>
        /// <param name="html">html文本</param>
        /// <param name="length">指定长度</param>
        /// <returns></returns>
        public static string ClearHtmlTags(string html, int length)
        {
            return CutString(StripTags(html), length);
        }

        /// <summary>
        /// 过滤除换行外的HTML标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string DropHtmlTags(string html)
        {
            html = html.Replace("<br />", "[br]").Replace("<br>", "[br]").Replace("</p>", "[br]");
            html = Regex.Replace(html, @"<(.*?)>", "", RegexOptions.IgnoreCase);
            html = html.Replace("[br]", "<br />");
            return html;
        }
        #endregion

        #region 截取字符长度
        /// <summary>
        /// 截取字符长度
        /// </summary>
        /// <param name="input">字符</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string CutString(object input, int len)
        {
            if (input == null)
            {
                return string.Empty;
            }
            return CutString(input.ToString(), len);
        }
        /// <summary>
        /// 截取字符长度
        /// </summary>
        /// <param name="input">字符</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string CutString(string input, int len)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "";
            }
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(input);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }

                try
                {
                    tempString += input.Substring(i, 1);
                }
                catch
                {
                    break;
                }

                if (tempLen > len)
                    break;
            }
            //如果截过则加上半个省略号 
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(input);
            if (mybyte.Length > len)
                tempString += "…";
            return tempString;
        }
        #endregion

        /// <summary>
        /// 返回重复N次的字符串
        /// </summary>
        /// <param name="src"></param>
        /// <param name="times">重复次数</param>
        /// <returns></returns>
        public static string Repeat(string src, int times)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < times; i++)
            {
                sb.Append(src);
            }
            return sb.ToString();
        }

        #region StrReplace
        /// <summary>
        /// 非数字和字母全部替换成中划线
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StrReplace(string str)
        {
            string returnstr = Regex.Replace(str, @"\W", " ").Replace("_", " ").ToLower().Trim().Replace(" ", "-");
            returnstr = Regex.Replace(returnstr, @"-+", "-", RegexOptions.IgnoreCase);
            return returnstr;
        }
        #endregion

        #region 替换指定的字符串
        /// <summary>
        /// 替换指定的字符串
        /// </summary>
        /// <param name="originalStr">原字符串</param>
        /// <param name="oldStr">旧字符串</param>
        /// <param name="newStr">新字符串</param>
        /// <returns></returns>
        public static string ReplaceStr(string originalStr, string oldStr, string newStr)
        {
            if (string.IsNullOrEmpty(oldStr))
            {
                return "";
            }
            return originalStr.Replace(oldStr, newStr);
        }
        #endregion

        #region 检查&过滤危险字符

        /// <summary> 
        /// 检查过滤设定的危险字符
        /// </summary> 
        /// <param name="InText">要过滤的字符串 </param> 
        /// <returns>如果参数存在不安全字符，则返回true </returns> 
        public static bool SqlFilter(string word, string InText)
        {
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }


        #endregion

        #region 生成特定字符串

        /// <summary>
        /// 生成一个新的GUID，形如："EF3AB3CD6CF347888203EBC56873B962"
        /// </summary>
        /// <returns></returns>
        public static string GetGuid()
        {
            return System.Guid.NewGuid().ToString("N").ToUpper();
        }

        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <param name="pwdLength">密码的位数</param>
        /// <returns></returns>
        public static string GeneratePassword(int pwdLength)
        {
            string randomChars = "abcdefghijklmnopqrstuvwxyz1234567890";
            return GenerateRandText(randomChars, pwdLength);
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="randomChars">字符串</param>
        /// <param name="textLength">长度</param>
        /// <returns>随机串</returns>
        public static string GenerateRandText(string randomChars, int textLength)
        {
            StringBuilder text = new StringBuilder();
            int num = 0;
            Random random = new Random();
            for (int i = 0; i < textLength; i++)
            {
                num = random.Next(randomChars.Length);
                text.Append(randomChars[num]);
            }
            return text.ToString();
        }
        #endregion

        #region 判断字符是否包含中文
        public static bool IsChinese(string txt)
        {
            bool BoolValue = false;
            for (int i = 0; i < txt.Length; i++)
            {
                if (Convert.ToInt32(Convert.ToChar(txt.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))
                {
                    BoolValue = false;
                }
                else
                {
                    return BoolValue = true;
                }
            }
            return BoolValue;
        }
        #endregion

        #region 将字符串转换为字符串数组
        public static string[] StringToArr(string input, int len)
        {
            int arrLen = input.Length % len == 0 ? input.Length / len : input.Length / len + 1;
            string[] arrTemp = new string[arrLen];

            for (int i = 0; i < arrLen; i++)
            {
                //如果是最后一段
                if (i == arrLen - 1)
                {
                    arrTemp[i] = input.Substring(i * len);
                }
                else
                {
                    arrTemp[i] = input.Substring(i * len, len);
                }
            }
            return arrTemp;
        }
        #endregion

        #region 删除最后结尾的一个逗号
        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            if (str.Length < 1)
            {
                return "";
            }
            return str.Substring(0, str.LastIndexOf(","));
        }
        #endregion

    }
}
